package com.mxsoft.takeaway.web.controller;

import com.google.gson.Gson;
import com.mxsoft.takeaway.util.eleme.ElemeUtil;
import eleme.openapi.sdk.api.entity.other.OMessage;
import eleme.openapi.sdk.api.utils.CallbackValidationUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhangyingxuan
 */
@Slf4j
@RestController
@RequestMapping("/api/eleme")
public class ElemeCallbackController {

    @RequestMapping("/do")
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        try {
            String body = IOUtils.toString(request.getInputStream(), "UTF-8");
            if (StringUtils.isNotBlank(body)) {
                    log.info("request body :" + body);
            } else {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json");
                response.setStatus(HttpServletResponse.SC_OK);
                response.getWriter().write("{\"message\":\"ok\"}");
                response.flushBuffer();
                return;
            }

            Gson gson = new Gson();

            boolean validMessage = CallbackValidationUtil.isValidMessage(gson.fromJson(body, OMessage.class), ElemeUtil.getConfig().getApp_secret());
            if (!validMessage) {
                log.error("无效的消息");
            }

            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().write("{\"message\":\"ok\"}");
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




}
